import sys
import os
from mqtt_conf import*


def on_message(msg):
    try:
        cmd = msg.decode('utf-8', 'ignore')
    except:
        print(msg)
        return
    try:
        print(cmd, end='')
    except:
        pass


if __name__ == '__main__':
    import mqtt_conf
    columns, lines = os.get_terminal_size()
    set_on_message(on_message)
    read_config('mqtt.ini')
    start_loop()
    mqtt_conf.client.subscribe(f'lily/{client_id}/cmd')
    print(f'rows {lines-1} cols {columns}')
    mqtt_out(f'pty -r')
    mqtt_out(f'stty rows {lines-1} cols {columns}')
    mqtt_out(f'export TERM=xterm-256color')
    print('[listening]')
    mqtt_conf.client.publish(f'sys/{mqtt_conf.client_id}/ping', 'Service ON')
    mqtt_conf.client.publish(f'sys/{mqtt_conf.client_id}/time')
    while 1:
        try:
            cmd = input() + '\n'
        except KeyboardInterrupt:
            sys.stdout.write(f'\x1b[{lines}f')
            s = input('[wsadeqbxoWn-]')
            repeat = 1
            if len(s) > 1:
                try:
                    repeat = int(s[1:].strip())
                except:
                    pass

            if not s:
                cmd = '\x03'
            elif s[0] == 'w':
                cmd = '\x1b[A'
            elif s[0] == 's':
                cmd = '\x1b[B'
            elif s[0] == 'a':
                cmd = '\x1b[D'
            elif s[0] == 'd':
                cmd = '\x1b[C'
            elif s == 'e':
                cmd = '\x1b\x1b'
            elif s == 'q':
                break
            elif s[0] == 'x':
                cmd = '\x18'
            elif s[0] == 'o':
                cmd = '\x0f'
            elif s[0] == 'W':
                cmd = '\x17'
            elif s[0] == 'b':
                cmd = '\x08'
            elif s[0] == 'n':
                cmd = '\r\n'
            elif s[0] == '-':
                cmd = s[1:]
            else:
                cmd = s
            cmd = cmd * repeat
        except EOFError:
            s = input('[quit? y/n]')
            if s == 'y' or s == 'Y' or s == 'yes' or s == 'YES' or s == 'q':
                break
            cmd = '\x04'

        mqtt_out(cmd, end='')
    print('[exit]')
    stop_loop()
